package servlets.user;

import hibernate.method.UserMethods;
import hibernate.model.User;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Servlet implementation class UserDetails
 */
@WebServlet("/UserDetails")
public class UserDetails extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserDetails() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String req = request.getParameter("userID");
		int userID = Integer.parseInt(req);
		response.setContentType("text/plain");
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session s = sessionFactory.openSession();
		s.beginTransaction();
		UserMethods u_m = new UserMethods();
		User user = u_m.id_to_user(sessionFactory, s, userID);
		
		JSONObject json = new JSONObject();
		PrintWriter out = response.getWriter();
		try {
			json.put("username", user.getUsername());
			json.put("birthdate", user.getBirthdate());
			json.put("email", user.getEmail());
			json.put("add_date", user.getAdd_date());
			json.put("gender", user.getGender());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		out.println(json);
		out.flush();

		s.getTransaction().commit();
	}

}
